import { createRouter, createWebHashHistory, RouteRecordRaw , Router} from 'vue-router'

import Page404 from '@/views/guard/Page404.vue'
import DefaultLayout from '@/layout/DefaultLayout.vue'

import { useApplicationStore } from '@/stores'

import { routes as SystemRoutes } from './SystemRouter'
import { routes as AppRoutes } from './AppRouter'
import { useDzvCache } from '@/services'
export const guardRoutes = [
  {
    path: '/guard',
    component: DefaultLayout,
    redirect: '/404',
    children: [
      { 
        path: '/:pathMatch(.*)', 
        name: 'Page404', 
        component: Page404 
      }
    ],
  },
  
]


const routeSource = [
  ...SystemRoutes,
  ...AppRoutes,
];

export function dynamicRouter(appCode: string){
  const appRouter = routeSource.filter(c=>c.meta.app === appCode);
  appRouter.forEach(item => {
    router.addRoute(item);  
  });
  
}


export const router: Router = createRouter({
  history: createWebHashHistory(),
  routes: [
    // ...AppRoutes,
    // ...SystemRoutes,
    ...guardRoutes,
  ]
})

router.beforeEach((to, from) => {
  const appStore = useApplicationStore()
  appStore.beforeRouting()
  // ...
  // 返回 false 以取消导航
  return true
})

router.afterEach((to, from) => {
  const appStore = useApplicationStore()
  appStore.afterRouting()
  const cache = useDzvCache()
  cache.cache('LAST_ROUTER_FULLPATH', to.fullPath)
  return true
})